//
//  LogIn.m
//  LilyBBS
//
//  Created by 李行 on 11-11-27.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "LogIn.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "RegexKitLite.h"
#import "SingleCookie.h"
#import "Reachability.h"

@implementation LogIn

@synthesize username,password,scrollView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    UIBarButtonItem* rightBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done:)];
    UIBarButtonItem* leftBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel:)];
    
    self.navigationItem.rightBarButtonItem = rightBarButton;
    self.navigationItem.leftBarButtonItem = leftBarButton;
    //[rightBarButton release];
    //[leftBarButton release];
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    // Do any additional setup after loading the view from its nib.
    self.scrollView.contentSize = self.view.frame.size;
    self.password.delegate = self;
    [self.username becomeFirstResponder];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    name = [NSString stringWithFormat:@"%@",self.username.text];
    pwd = [NSString stringWithFormat:@"%@",self.password.text];
    //name = [NSString stringWithString:@"lixing111"];
    //pwd = [NSString stringWithString:@"188402"];
    
    int value = random()%100000;
    [SingleCookie sharedSingleCookie].randomNumber = [NSString stringWithFormat:@"%d",value];
    NSString* urlString = [NSString stringWithFormat:@"http://bbs.nju.edu.cn/vd%d/bbslogin?type=2",value];
    NSURL* url = [[NSURL alloc] initWithString:urlString];
    //[urlString release];
    ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:url];
    //[url release];
    [request setPostValue:name forKey:@"id"];
    [request setPostValue:pwd forKey:@"pw"];
    [request startSynchronous];
    NSError *error = [request error];
    NSString* response;
    if (!error) {
        response = [request responseString];
    }
    //[request release];
    if (![response isMatchedByRegex:@"setCookie"]) {
        //NSLog(@"登录不成功！");
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"登录提示" message:@"登录不成功，请重新登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        //[alert release];
    }else{
        //NSLog(@"登录成功！");
        /*UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"登录提示" message:@"登录成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];*/
        //将cookie信息保存到文件中
        /*NSError* error;
         NSFileManager* manager = [NSFileManager defaultManager];
         NSString* documentDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
         NSString* cookiePath = [documentDir stringByAppendingPathComponent:@"cookies"];
         //如何保存cookie的文件不存在，则创建之
         if (![manager fileExistsAtPath:cookiePath]) {
         //取得Net.BBS.SetCookie后的字符串，为保存cookie作准备
         NSString* regex = [[NSString alloc]initWithFormat:@"(?<=\\(\\')[\\w\\W]*(?=\\'\\))"];
         NSString* results = [response stringByMatching:regex];
         NSLog(@"%@",results);
         //将cookie保存到文件中
         [results writeToFile:cookiePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
         NSString* cookieData = [NSString stringWithContentsOfFile:cookiePath];
         }*/
        
        NSString* regex = [[NSString alloc]initWithFormat:@"(?<=\\(\\')[\\w\\W]*(?=\\'\\))"];
        NSString* result = [response stringByMatching:regex];
        NSString* _U_NUM1 = [result stringByMatching:@"[\\w\\W]*(?=N)"];
        NSInteger* _U_NUMInteger = [_U_NUM1 integerValue]+2;
        NSString* _U_NUM = [[NSString alloc] initWithFormat:@"%d",_U_NUMInteger];
        //NSLog(@"_U_NUM:%d",_U_NUMInteger);
        NSString* _U_UID = [result stringByMatching:@"(?<=N)[\\w\\W]*(?=\\+)"];
        //NSLog(@"_U_UID:%@",_U_UID);
        NSString* _U_KEY1 = [result stringByMatching:@"(?<=\\+)[\\w\\W]*"];
        NSInteger* _U_KEYInteger = [_U_KEY1 integerValue]-2;
        NSString* _U_KEY = [[NSString alloc] initWithFormat:@"%d",_U_KEYInteger];
        //NSLog(@"_U_KEY:%@",_U_KEY);
        
        //create a _U_NUM cookie
        NSString* path = [NSString stringWithFormat:@"/vd/%d/",value];
        NSDictionary *numproperties = [[NSMutableDictionary alloc] init];
        [numproperties setValue:@"_U_NUM" forKey:NSHTTPCookieName];
        [numproperties setValue:_U_NUM  forKey:NSHTTPCookieValue];
        [numproperties setValue:@"bbs.nju.edu.cn" forKey:NSHTTPCookieDomain];
        [numproperties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCookieExpires];
        [numproperties setValue:path forKey:NSHTTPCookiePath];
        NSHTTPCookie *num = [[NSHTTPCookie alloc] initWithProperties:numproperties]; 
        //create a _U_UID cookie
        NSDictionary* uidproperties = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       @"_U_UID",NSHTTPCookieName,
                                       _U_UID,NSHTTPCookieValue,
                                       @"bbs.nju.edu.cn",NSHTTPCookieDomain,
                                       path,NSHTTPCookiePath,
                                       [NSDate dateWithTimeIntervalSinceNow:60*60],NSHTTPCookieExpires,
                                       nil];
        NSHTTPCookie* uid = [[NSHTTPCookie alloc]initWithProperties:uidproperties];
        //create a _U_KEY cookie
        NSDictionary* keyproperties = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       @"_U_KEY",NSHTTPCookieName,
                                       _U_KEY,NSHTTPCookieValue,
                                       @"bbs.nju.edu.cn",NSHTTPCookieDomain,
                                       path,NSHTTPCookiePath,
                                       [NSDate dateWithTimeIntervalSinceNow:60*60],NSHTTPCookieExpires,
                                       nil];
        NSHTTPCookie* key = [[NSHTTPCookie alloc]initWithProperties:keyproperties];
        //将cookies存放在SingleCookie中的savedCookies
        [SingleCookie sharedSingleCookie].savedCookies = [NSMutableArray arrayWithObjects:num,uid,key, nil];
        [self dismissModalViewControllerAnimated:YES];
        //[_U_NUM release];
        //[_U_KEY release];
    }

    return YES;
}


-(IBAction)done:(id)sender{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.nju.edu.cn"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            //没有网络连接
            NSLog(@" ");
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络好像连接不上。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        case ReachableViaWWAN:
            //使用3G网络            
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络            
            break;
    }
    
    name = [NSString stringWithFormat:self.username.text];
    pwd = [NSString stringWithFormat:self.password.text];
    //NSLog(@"name:%@",name);
    if(![name isMatchedByRegex:@"[A-Za-z0-9]{2,12}"]){
        name = [NSString stringWithString:@"lixing111"];
        pwd = [NSString stringWithString:@"188402"];
    }
    //检测输入的用户名和密码是否符合要求
    if(![name isMatchedByRegex:@"[A-Za-z0-9]{2,12}"]){
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"登录提示" message:@"请输入正确的用户名！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        [self.username becomeFirstResponder];
		return;
	}
	if([pwd isEqualToString:@""]){
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"登录提示" message:@"请输入正确的密码！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        [self.password becomeFirstResponder];
		return;
	}
    //进行登录连接
    NSInteger* value = random()%100000;
    [SingleCookie sharedSingleCookie].randomNumber = [NSString stringWithFormat:@"%d",value];
    //NSLog(@"%@",[SingleCookie sharedSingleCookie].randomNumber);
    NSString* urlString = [NSString stringWithFormat:@"http://bbs.nju.edu.cn/vd%d/bbslogin?type=2",value];
    //NSLog(@"%@",urlString);
    NSURL* url = [[NSURL alloc] initWithString:urlString];
    //[urlString release];
    ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:url];
    [request setPostValue:name forKey:@"id"];
    [request setPostValue:pwd forKey:@"pw"];
    [request startSynchronous];
    NSError *error = [request error];
    NSString* response;
    if (!error) {
        response = [request responseString];
        //NSLog(@"%@",response);
    }
    //检测是否登录成功
    if (![response isMatchedByRegex:@"setCookie"]) {
        //NSLog(@"登录不成功！");
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"登录提示" message:@"登录不成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        return;
    }else{
        //NSLog(@"登录成功！");
        /*UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"登录提示" message:@"登录成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];*/
        //将cookie信息保存到文件中
        /*NSError* error;
        NSFileManager* manager = [NSFileManager defaultManager];
        NSString* documentDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSString* cookiePath = [documentDir stringByAppendingPathComponent:@"cookies"];
        //如何保存cookie的文件不存在，则创建之
        if (![manager fileExistsAtPath:cookiePath]) {
            //取得Net.BBS.SetCookie后的字符串，为保存cookie作准备
            NSString* regex = [[NSString alloc]initWithFormat:@"(?<=\\(\\')[\\w\\W]*(?=\\'\\))"];
            NSString* results = [response stringByMatching:regex];
            NSLog(@"%@",results);
            //将cookie保存到文件中
            [results writeToFile:cookiePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
            NSString* cookieData = [NSString stringWithContentsOfFile:cookiePath];
        }*/
        //设置cookie
        //取出设置cookie所需要的关键字符串
        NSString* regex = [[NSString alloc]initWithFormat:@"(?<=\\(\\')[\\w\\W]*(?=\\'\\))"];
        NSString* result = [response stringByMatching:regex];
        NSString* _U_NUM1 = [result stringByMatching:@"[\\w\\W]*(?=N)"];
         NSInteger* _U_NUMInteger = [_U_NUM1 integerValue]+2;
         NSString* _U_NUM = [[NSString alloc] initWithFormat:@"%d",_U_NUMInteger];
         //NSLog(@"_U_NUM:%d",_U_NUMInteger);
         NSString* _U_UID = [result stringByMatching:@"(?<=N)[\\w\\W]*(?=\\+)"];
         //NSLog(@"_U_UID:%@",_U_UID);
         NSString* _U_KEY1 = [result stringByMatching:@"(?<=\\+)[\\w\\W]*"];
         NSInteger* _U_KEYInteger = [_U_KEY1 integerValue]-2;
         NSString* _U_KEY = [[NSString alloc] initWithFormat:@"%d",_U_KEYInteger];
         //NSLog(@"_U_KEY:%@",_U_KEY);
         
        //create a _U_NUM cookie
         NSString* path = [NSString stringWithFormat:@"/vd/%d/",value];
         NSDictionary *numproperties = [[NSMutableDictionary alloc] init];
         [numproperties setValue:@"_U_NUM" forKey:NSHTTPCookieName];
         [numproperties setValue:_U_NUM  forKey:NSHTTPCookieValue];
         [numproperties setValue:@"bbs.nju.edu.cn" forKey:NSHTTPCookieDomain];
         [numproperties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCookieExpires];
         [numproperties setValue:path forKey:NSHTTPCookiePath];
         NSHTTPCookie *num = [[NSHTTPCookie alloc] initWithProperties:numproperties]; 
        //create a _U_UID cookie
         NSDictionary* uidproperties = [NSMutableDictionary dictionaryWithObjectsAndKeys:
         @"_U_UID",NSHTTPCookieName,
         _U_UID,NSHTTPCookieValue,
         @"bbs.nju.edu.cn",NSHTTPCookieDomain,
         path,NSHTTPCookiePath,
         [NSDate dateWithTimeIntervalSinceNow:60*60*24],NSHTTPCookieExpires,
         nil];
         NSHTTPCookie* uid = [[NSHTTPCookie alloc]initWithProperties:uidproperties];
        //create a _U_KEY cookie
         NSDictionary* keyproperties = [NSMutableDictionary dictionaryWithObjectsAndKeys:
         @"_U_KEY",NSHTTPCookieName,
         _U_KEY,NSHTTPCookieValue,
         @"bbs.nju.edu.cn",NSHTTPCookieDomain,
         path,NSHTTPCookiePath,
         [NSDate dateWithTimeIntervalSinceNow:60*60],NSHTTPCookieExpires,
         nil];
         NSHTTPCookie* key = [[NSHTTPCookie alloc]initWithProperties:keyproperties];
        //将cookies存放在SingleCookie中的savedCookies
        [SingleCookie sharedSingleCookie].savedCookies = [NSMutableArray arrayWithObjects:num,uid,key, nil];
        
        [self dismissModalViewControllerAnimated:YES];
        //[request release];
    }
}

-(IBAction)cancel:(id)sender{
    [self dismissModalViewControllerAnimated:YES];
}

@end
